import React, { useEffect, useState } from 'react';
import { Tag } from 'antd';
import { ITagSelectProps, ITagOptionProps } from './type';

const { CheckableTag } = Tag;

const TagOption: React.FC<ITagOptionProps> = React.memo(
  ({ children, onChange, checked, value }) => {
    return (
      <CheckableTag
        checked={checked ?? false}
        onChange={(state) => onChange && onChange(value, state)}
        key={value}
      >
        {children}
      </CheckableTag>
    );
  },
);

export const TagSelect: React.FC<ITagSelectProps> & { Option: typeof TagOption } = ({
  children,
  onChange,
  ...otherProps
}) => {
  const [checked, setChecked] = useState('');

  useEffect(() => {
    if (String(otherProps?.value)) {
      setChecked(String(otherProps?.value));
    }
  }, [otherProps?.value]);

  const onHandleChange = React.useCallback(
    (value: any, state: any) => {
      if (value && state) {
        setChecked(value);
      } else {
        setChecked('');
      }
      if (!!onChange) {
        onChange(value ?? '');
      }
    },
    [children],
  );

  return (
    <>
      {React.Children.map(children, (child: any) => {
        return React.cloneElement(child, {
          value: child?.props?.value,
          onChange: onHandleChange,
          key: `tag-select-${Math.random()}`,
          checked: String(child?.props?.value) === String(checked),
        });
      })}
    </>
  );
};

TagSelect.Option = TagOption;
